package ru.papergames.model.proxies
{
	import by.andronix.logger.Logger;
	
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	import org.puremvc.as3.interfaces.IFacade;

	public class BaseResponder implements IResponder
	{
		
		public var resultFunction:Function;
		public var faultFunction:Function;
		
		public var method:String;
		
		protected var facade:IFacade;		
		
		private var _resultNote:String;
		private var _faultNote:String;
		private var _globalCompleteNote:String;
		
		public function BaseResponder(	facade:IFacade, 
										resultNote:String, faultNote:String, 
										globalCompleteNote:String = null)
		{
			super();
			this.facade = facade;
			this._resultNote = resultNote;
			this._faultNote = faultNote;
			this._globalCompleteNote = globalCompleteNote;
		}

		public function result(data:Object):void
		{
			var result:ResultEvent = data as ResultEvent;
			
			if (resultFunction is Function) {
				var response:XML = result.result as XML; 
				
				//validate response format
				
				if (response) {
				
					Logger.getLogger(this).debug(this._resultNote + ":\n" + response.toXMLString());	
					
					response.@method = method;
					
					if (this.facade && this._resultNote) this.facade.sendNotification( resultFunction(response), response);					
					
				
				} else {
					Logger.getLogger(this).error('Wrong XML format in response!');
					if (this.facade && this._faultNote) 
						this.facade.sendNotification(this._faultNote);
				}
				
			}
			
			finish();
		}
		
		public function fault(data:Object):void
		{
			var fault:FaultEvent = data as FaultEvent;
			
			if (faultFunction is Function) {
				//get page content for the error - such as 500
				var answerBody:String = fault.fault.faultDetail;
				var errorString:String = fault.fault.faultString ;
				if (answerBody) {
					errorString += "\n" + answerBody.replace(/<[^>]+>/gi, '');
				}
				faultFunction(errorString);
				if (this.facade && this._faultNote) this.facade.sendNotification(this._faultNote);
			}
			
			finish();
		}
		
		protected function finish():void {
			if (this.facade && this._globalCompleteNote) 
					this.facade.sendNotification( this._globalCompleteNote, this._resultNote );
			
			this.facade = null;
			this._resultNote = null;
			this._faultNote = null;
			this._globalCompleteNote = null;
			this.resultFunction = null;
			this.faultFunction = null;
		}
		
	}
}